<template>
  <el-card class="box-card">
    <!-- 查询条件 -->
    <el-row class="search-el-row">
      <el-col :span="5">
        <div class="demo-input-size">
          <el-input v-model="listQuery.searchString" class="m-2" placeholder="Job关键字" />
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="demo-input-size">
          <el-button type="primary" :icon="Search" @click="JobQuery(true)">查询</el-button>
        </div>
      </el-col>
      <el-col :span="2">
        <div class="demo-input-size">
          <el-button type="primary" @click="addJob" :icon="Plus">新增</el-button>
        </div>
      </el-col>
      <el-col :span="2">
        <div class="demo-input-size">
          <el-button type="primary" v-if="!expand" :icon="RemoveFilled" @click="JobQuery(true)">展开</el-button>
          <el-button type="primary" v-if="expand" :icon="CirclePlusFilled" @click="JobQuery(false)">折叠</el-button>
        </div>
      </el-col> 
    </el-row>

    <!-- 展示列表 -->
    <el-row>
      <el-col :span="24">
        <el-table :data="lists" :border="parentBorder" style="width: 100%" :default-expand-all="expand">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <el-table :data="props.row.jobInfoList" :border="childBorder">
                  <el-table-column prop="name" label="名称" width="100" />
                  <el-table-column prop="nextFireTime" label="下次执行时间" width="190" />
                  <el-table-column prop="previousFireTime" label="上次执行时间" width="190" />
                  <el-table-column prop="beginTime" label="开始时间" width="180" />
                  <el-table-column label="任务状态" width="80">
                    <template #default="{ row }">
                      <el-tag :type="statusLableFilter(row.TriggerState)">
                        {{ row.displayState }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="interval" label="间隔时长" width="80" />
                  <el-table-column label="操作">
                    <template #default="{ row }">
                      <div style="display: flex; align-items: center">


                        <el-button type="primary" size="small" v-if="row.triggerState == 0"
                          @click="StopJob(row.name, props.row.groupName)" :icon="VideoPause">暂停</el-button>

                          <el-button type="success" size="small" v-if="row.triggerState != 0"
                          @click="ResumeJob(row.name, props.row.groupName)" :icon="VideoPlay">继续</el-button>

                          <el-button type="success" size="small" @click="TriggerJob(row.name, props.row.groupName)"
                          :icon="Expand">立即执行</el-button>
                        

                          <el-button type="danger" size="small" @click="RemoveJob(row.name, props.row.groupName)"
                          :icon="Delete">删除</el-button> 
                          <el-button type="info" size="small" @click="StopJob(row.name, props.row.groupName)"
                          :icon="Edit">编辑--大家就自己完成</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="JOB任务组" prop="groupName" />
        </el-table>

      </el-col>
    </el-row>


    <!-- Dialog 对话框--新增修改菜单专用 -->
    <el-dialog v-model="dialogVisible" title="新增Job" width="60%" :before-close="handleClose">
      <el-form :model="jobForm" :rules="roleRules" ref="addmenuFormRef" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="Job业务文件" prop="imageUrl">
              <el-upload class="avatar-uploader" :action="fileuploadUrl" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <el-icon class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="dll名称">
              <el-input v-model="jobForm.dllName" placeholder="dll名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="job实现类">
              <el-input v-model="jobForm.jobInstanceName" placeholder="job实现类全名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="job分组">
              <el-select v-model="jobForm.jobGroup" filterable allow-create default-first-option :reserve-keyword="false"
                placeholder="请选择或者输入Job分组">
                <el-option v-for="item in jobgroupList" :key="item.value" :label="item.text" :value="item.value"
                  style="width: 100%" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="job名称">
              <el-input v-model="jobForm.jobName" placeholder="job名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="trigger类型">
          <el-tree-select v-model="jobForm.triggerType" :data="triggertype" :props="{
            value: 'value', label: 'text', children: 'children'
          }" check-strictly="true" change="selectMenu" :render-after-expand="false" placeholder="请选择">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="Cron表达式" v-if="jobForm.triggerType == 1">
          <el-input v-model="jobForm.cron" placeholder="Cron表达式" />
        </el-form-item>
        <el-row v-if="jobForm.triggerType == 2">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <div class="demo-range">
                <el-date-picker v-model="jobForm.beginTime" type="datetime" placeholder="Pick a Date"
                  format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s a" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker v-model="jobForm.endTime" type="datetime" placeholder="Pick a Date"
                format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD h:m:s a" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="jobForm.triggerType == 2">
          <el-col :span="12">
            <el-form-item label="执行次数">
              <el-input v-model="jobForm.runTimes" placeholder="执行次数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="间隔时间">
              <el-input v-model="jobForm.intervalSecond" placeholder="间隔时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="job描述">
          <el-input v-model="jobForm.description" type="textarea" placeholder="job描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消</el-button>
          <el-button type="primary" @click="subJobForm(addmenuFormRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed, markRaw } from 'vue'
import axios from '../../../../api/index';
import { apiUrl } from "../../../../common/index"
import { ElMessageBox, ElMessage } from 'element-plus'
import { Plus, Delete, Edit, Search, Expand, VideoPause, VideoPlay,RemoveFilled,CirclePlusFilled } from '@element-plus/icons-vue'

//上传dll 文件----api地址
const fileuploadUrl = `${apiUrl()}job/UploadDllFile`;


const parentBorder = ref(false)
const childBorder = ref(false)


const listQuery = reactive({
  searchString: ''  //查询条件
});


const expand = ref(true); //控制属性table是展开还是折叠

let lists = ref([]); //Job详细列表

//初始化数据
onMounted(async () => {
 
  setInterval(() => {
    JobQuery(expand.value);
  }, 2000) 
})


//获取任务列表 
async function JobQuery(isexpand) {
  if (isexpand) {
    expand.value = true;
  }
  else {
    expand.value = false;
  }

  let reponse = await axios.get(`/job/GetAllJob`);
  let { data, success, message } = reponse.data;

  if (success) {
    lists.value = data;
  } else {
    console.log(message)
  }
}


const statusLableFilter = computed(() => item => {
  switch (item) {
    case 1:
      return 'success '
    case 2:
      return 'info'
    case 3:
      return 'warning'
    default:
      return item
  }
})

const statusTextFilter = computed(() => item => {
  switch (item) {
    case 1:
      return 'success '
    case 2:
      return 'info'
    case 3:
      return 'warning'
    default:
      return item
  }
})



//新增job弹框绑定的额数据
const jobForm = ref({
  jobName: "",
  jobGroup: "",
  selectJobGroup: "",
  dllName: "",
  jobInstanceName: "",
  beginTime: "2023-05-16T07:43:40.454Z",
  endTime: "2023-05-16T07:43:40.454Z",
  cron: "",
  runTimes: 0,
  intervalSecond: 0,
  triggerType: 1,
  description: ""
});


const jobgroupList = ref([]);
const triggertype = ref([{
  value: 2,
  text: "简单类型"
}, {
  value: 1,
  text: "Corn表达式"
}]);


//控制新增Job的弹框
const dialogVisible = ref(false)
const addJob = async () => {
  jobForm.value = {
    jobName: "",
    jobGroup: "",
    selectJobGroup: "",
    dllName: "",
    jobInstanceName: "",
    beginTime: "",
    endTime: "",
    cron: "",
    runTimes: 0,
    intervalSecond: 0,
    triggerType: 1,
    description: ""
  };
  jobgroupList.value = [];
  var reponse = await axios.get(`/Job/GetAllGroup`);
  let { data, success, message } = reponse.data;
  if (success) {
    jobgroupList.value = data;
  } else {
    ElMessageBox.alert("获取树列表失败");
  }
  dialogVisible.value = true;
}




//提交
let subJobForm = async (jobform) => {

var reponse = await axios.post(`/Job/AddJob`, jobForm.value);
let { message, success } = reponse.data;
if (success) {
  ElMessage({
    type: 'success',
    message: message,
  })
  dialogVisible.value = false;
  JobQuery(expand.value);
} else {
  ElMessageBox.alert(message);
}




// await jobform.validate(async (valid, fields) => {
//   if (valid) {
//     var reponse = await axios.post(`/Job/AddJob`, jobForm.value);
//     let { message, success } = reponse.data;
//     if (success) {
//       ElMessage({
//         type: 'success',
//         message: message,
//       })
//       dialogVisible.value = false;
//       JobQuery();
//     } else {
//       ElMessageBox.alert(message);
//     }
//   }
//   else {
//     console.error('校验失败');
//   }
// });
}



//暂停任务
const StopJob = async (name, group) => {
  var url = `/Job/StopJob/${name}/${group}`;
  var reponse = await axios.get(url);
  let { message, success } = reponse.data;
  if (success) {
    ElMessage({
      type: 'success',
      message: message,
    }) 
    JobQuery(expand.value);
  } else {
    ElMessageBox.alert(message);
  }
}



//恢复任务
const ResumeJob = async (name, group) => {
  var url = `/Job/ResumeJob/${name}/${group}`;
  var reponse = await axios.get(url);
  let { message, success } = reponse.data; 
  if (success) {
    ElMessage({
      type: 'success',
      message: message,
    })
    JobQuery(expand.value);
  } else {
    ElMessageBox.alert(message);
  }
}




//立即执行一次
const TriggerJob = async (name, group) => {
  var url = `/Job/TriggerJob/${name}/${group}`;
  var reponse = await axios.get(url);
  let { message, success } = reponse.data;
  if (success) {
    ElMessage({
      type: 'success',
      message: message,
    })
    JobQuery(expand.value);
  } else {
    ElMessageBox.alert(message);
  }
}





//删除任务
const RemoveJob = async (name, group) => {
  ElMessageBox.confirm(
    `确定删除Job ?`,
    '删除??',
    {
      type: 'warning',
      icon: markRaw(Delete),
    }
  ).then(async () => {
    var url = `/Job/RemoveJob/${name}/${group}`;
    var reponse = await axios.get(url);
    let { message, success } = reponse.data;
    if (success) {
      ElMessage({
        type: 'success',
        message: message,
      })
      dialogVisible.value = false;
      JobQuery(expand.value);
    } else {
      ElMessageBox.alert(message);
    }
  });
}


//文件上传前触发的行为
const beforeAvatarUpload = (uploadFile) => {
  console.log(uploadFile);
}

///文件上传成功后，api响应了结果了，触发这里？
const handleAvatarSuccess = (response, uploadFile, uploadFiles) => {
  if (response.success) {
    jobForm.value.dllName = response.data.dllName;
    jobForm.value.jobInstanceName = response.data.typeName;
  }
}







</script>